<template>
	<view class="container">
		<uni-indexed-list :options="workerList " :showSelect="true" @click="onclick"></uni-indexed-list>
		<view class="btn" @click="confirm">
			选好了
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		api_employee_list,
	} from "../../../../../apis/apis.js"
	import {
		useMainStore
	} from '@/utils/store.js';
	import {
		onLoad,
		onShow
	} from "@dcloudio/uni-app"
	import {
		pinyin
	}
	from "pinyin-pro";

	const store = ref(useMainStore());

	const workerList = ref([]); //主管列表
	const selectWorkerList = ref([])
	const orderServiceId = ref(0);
	const popup = ref(null)


	// 将名字转换为首字母
	function getFirstLetter(name) {
		return pinyin(name, {
			pattern: 'first',
			toneType: 'none',
		})[0].toUpperCase();
	}


	//点击一个成员
	const onclick = async (e) => {
		console.log("点击了", e);
		if (store.value.selectedWorker.some(item => item.id == e.item.id)) { //不能重复
			uni.showToast({
				title: "已经选过了",
				icon: "error"
			});
			return;
		} else {
			selectWorkerList.value = e.select;
			console.log("selectWorkerList", selectWorkerList.value);
		}
	};


	//确认选择的师傅
	const confirm = () => {
		for (let i = 0; i < selectWorkerList.value.length; i++) {
			store.value.set_selectedWorker(selectWorkerList.value[i]); //存入pinia
		}
		console.log("store.value.selectedWorker", store.value.selectedWorker);
		uni.navigateBack({
			delta: 1,
			succes() {
				uni.showToast({
					title: "完成!",
					icon: 'success'
				});
			}
		});
	}


	onLoad(async () => {
		store.value.clear_selectedWorker();
		//获取师傅列表
		try {
			let res = await api_employee_list({
				jobId: 4
			});
			if (res.data && res.data.length > 0) {
				// 创建一个映射，用于存储每个字母对应的师傅对象列表
				const letterMap = {};
				res.data.forEach(item => {
					const firstLetter = getFirstLetter(item.name);
					if (!letterMap[firstLetter]) {
						letterMap[firstLetter] = [];
					}
					letterMap[firstLetter].push({
						id: item.id,
						name: item.name
					});
				});

				// 将映射转换为所需的格式
				const processedList = Object.keys(letterMap).sort().map(letter => ({
					letter,
					data: letterMap[letter].sort((a, b) => a.name.localeCompare(b.name))
				}));

				workerList.value = processedList;
				console.log(workerList.value);
			}
		} catch (e) {
			uni.showToast({
				title: e.msg || "出错了",
				icon: "none"
			});
		}
	});
</script>

<style lang="scss" scoped>
	.container {
		width: 750rpx;

		.btn {
			width: 700rpx;
			height: 80rpx;
			border-radius: 10rpx;
			margin-left: 25rpx;
			overflow: hidden;
			background-color: $primary-color;
			font-family: Alibaba_PuHuiTi_Regular;
			font-weight: 400;
			font-size: 38rpx;
			color: white;
			display: flex;
			justify-content: center;
			align-items: center;
			// margin-top: 50rpx;
			position: absolute;
			bottom: calc(env(safe-area-inset-bottom) + 10rpx);
		}

	}
</style>